from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from news.core.exceptions import NotFoundException, ValidationException
from news.core.serializers.news import (
    NewsCreateSerializer,
    NewsDeleteSerializer,
    NewsDetailSerializer,
    NewsListSerializer,
    NewsUpdateSerializer,
)
from news.core.services.news import NewsService


class NewsCreateView(APIView):
    """
    post:
    创建新闻
    
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          properties:
            title:
              type: string
            content:
              type: string
            category:
              type: string
    """
    serializer_class = NewsCreateSerializer
    def post(self, request):
        try:
            news_dto = NewsService().create_news(request.data)
            return Response({
                'success': True,
                'data': {
                    'id': news_dto.id,
                    'title': news_dto.title,
                    'subtitle': news_dto.subtitle,
                    'content': news_dto.content,
                    'content_div': news_dto.content_div,
                    'category': news_dto.category,
                    'status': news_dto.status,
                    'created_at': news_dto.created_at.isoformat(),
                    'updated_at': news_dto.updated_at.isoformat(),
                    'image_list': news_dto.image_list,
                    'video_list': news_dto.video_list,
                    'audio_list': news_dto.audio_list,
                    'editor': news_dto.editor,
                    'link': news_dto.link,
                    'source': news_dto.source,
                    'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                    'origin_id': news_dto.origin_id
                }
            }, status=status.HTTP_201_CREATED)
        except ValidationException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class NewsDetailView(APIView):
    """
    get:
    获取新闻详情
    
    parameters:
      - name: news_id
        in: path
        type: integer
        required: true
    """
    serializer_class = NewsDetailSerializer
    def get(self, request, news_id):
        try:
            news_dto = NewsService().get_news(news_id)
            return Response({
                'success': True,
                'data': {
                    'id': news_dto.id,
                    'title': news_dto.title,
                    'subtitle': news_dto.subtitle,
                    'content': news_dto.content,
                    'content_div': news_dto.content_div,
                    'category': news_dto.category,
                    'status': news_dto.status,
                    'created_at': news_dto.created_at.isoformat(),
                    'updated_at': news_dto.updated_at.isoformat(),
                    'image_list': news_dto.image_list,
                    'video_list': news_dto.video_list,
                    'audio_list': news_dto.audio_list,
                    'editor': news_dto.editor,
                    'link': news_dto.link,
                    'source': news_dto.source,
                    'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                    'origin_id': news_dto.origin_id
                }
            })
        except NotFoundException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class NewsUpdateView(APIView):
    """
    put:
    更新新闻
    
    parameters:
      - name: news_id
        in: path
        type: integer
        required: true
      - name: body
        in: body
        required: true
        schema:
          type: object
          properties:
            title:
              type: string
            content:
              type: string
            category:
              type: string
            status:
              type: string
    """
    serializer_class = NewsUpdateSerializer
    def put(self, request, news_id):
        try:
            news_dto = NewsService().update_news(news_id, request.data)
            return Response({
                'success': True,
                'data': {
                    'id': news_dto.id,
                    'title': news_dto.title,
                    'subtitle': news_dto.subtitle,
                    'content': news_dto.content,
                    'content_div': news_dto.content_div,
                    'category': news_dto.category,
                    'status': news_dto.status,
                    'created_at': news_dto.created_at.isoformat(),
                    'updated_at': news_dto.updated_at.isoformat(),
                    'image_list': news_dto.image_list,
                    'video_list': news_dto.video_list,
                    'audio_list': news_dto.audio_list,
                    'editor': news_dto.editor,
                    'link': news_dto.link,
                    'source': news_dto.source,
                    'release_date': news_dto.release_date.isoformat() if news_dto.release_date else None,
                    'origin_id': news_dto.origin_id
                }
            })
        except NotFoundException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except ValidationException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class NewsDeleteView(APIView):
    """
    delete:
    删除新闻
    
    parameters:
      - name: news_id
        in: path
        type: integer
        required: true
      - name: body
        in: body
        required: true
        schema:
          type: object
          properties:
            confirm:
              type: boolean
              description: 必须设置为true才能执行删除操作
    """
    serializer_class = NewsDeleteSerializer
    
    def delete(self, request, news_id):
        try:
            serializer = self.serializer_class(data={
                'id': news_id,
                'confirm': request.data.get('confirm', False)
            })
            serializer.is_valid(raise_exception=True)
            
            if not serializer.validated_data['confirm']:
                raise ValidationException("删除操作必须明确确认")
                
            success = NewsService().delete_news(news_id)
            if not success:
                raise NotFoundException("News item not found")
                
            return Response({
                'success': True,
                'message': 'News deleted successfully'
            })
        except ValidationException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except NotFoundException as e:
            return Response({
                'success': False,
                'error': e.message
            }, status=e.code)
        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class NewsListByCategoryView(APIView):
    """
    get:
    按分类获取新闻列表
    
    parameters:
      - name: category
        in: path
        type: string
        required: true
      - name: page
        in: query
        type: integer
        required: false
      - name: page_size
        in: query
        type: integer
        required: false
    """
    serializer_class = NewsListSerializer
    def get(self, request, category):
        try:
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('page_size', 10))
            news_list_dto = NewsService().list_news_by_category(category, page, page_size)
            return Response({
                'success': True,
                'data': {
                    'items': [{
                        'id': item.id,
                        'title': item.title,
                        'category': item.category,
                        'created_at': item.created_at.isoformat()
                    } for item in news_list_dto.items],
                    'total': news_list_dto.total,
                    'page': news_list_dto.page,
                    'page_size': news_list_dto.page_size
                }
            })
        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)